/**
 * static class Channel
 */

package nwsim;

import java.util.*;

public class Channel extends TimerTask {
	
	public static Queue<Message> pktQueue;
	boolean removable = true;
		
	public Channel() {
		pktQueue = new LinkedList<Message>();
		Timer dispatchTimer = new Timer();
		dispatchTimer.schedule(this, 0, Constants.channelTimer);
	}
	
	public void run() {
		synchronized(this) {
			if(!pktQueue.isEmpty()) {
				if(removable) { //used element
					pktQueue.remove();
				}
			}
			
			if(!pktQueue.isEmpty()) {
				notifyAll();
				removable = true;
			}
		}
	}
		
	public synchronized void sendToChannel(Message msg) {
		if(pktQueue.isEmpty()) { //adding to empty queue, don't remove on task run, remove after notifying once
			removable = false;
		}
		pktQueue.add(msg);
	}
	
	public Message recvFromChannel() {
			if(!pktQueue.isEmpty())
				return pktQueue.element();
			else
				return null;
	}
}
